package com.mingtu.guards.activity;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.imageview.ShapeableImageView;
import com.luck.picture.lib.basic.PictureMediaScannerConnection;
import com.luck.picture.lib.basic.PictureSelectionPreviewModel;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnCallbackListener;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.TitleBarStyle;
import com.luck.picture.lib.utils.DownloadFileUtils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.core.CenterPopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.lxj.xpopup.util.XPopupUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.Eventbus.MyEventBus;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.IntentUtils;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.ScreenUtils;
import com.mingtu.common.view.ContainsEmojiEditText;
import com.mingtu.guards.R;
import com.mingtu.guards.adapter.InfraredRecAdapter;
import com.mingtu.guards.base.MyBaseActivity;
import com.mingtu.guards.bean.InfraredRecordImgBean;
import com.mingtu.guards.share.BottomPopupShare2;
import com.mingtu.guards.utils.MyConstant;
import com.mob.MobSDK;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.listener.OnPageChangeListener;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.wechat.favorite.WechatFavorite;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import static com.mingtu.guards.base.Application.hideMyDownLoadDialog;
import static com.mingtu.guards.base.Application.showMyDownLoadDialog;

public class InfraredRecordPicDetailsActivity extends MyBaseActivity {

    @BindView(R.id.iv_picture)
    ShapeableImageView ivPicture;
    @BindView(R.id.rb_but1)
    RadioButton rbBut1;
    @BindView(R.id.rb_but2)
    RadioButton rbBut2;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.tv_spec_name_ai)
    TextView tvSpecNameAi;
    @BindView(R.id.tv_num)
    TextView tvNum;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.but)
    Button but;
    @BindView(R.id.tv_spe_name)
    TextView tvSpeName;
    @BindView(R.id.tv_auth_level)
    TextView tvAuthLevel;
    @BindView(R.id.tv_auth_time)
    TextView tvAuthTime;
    @BindView(R.id.tv_remark)
    TextView tvRemark;
    @BindView(R.id.layout)
    LinearLayout layout;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.layout_auth)
    LinearLayout layoutAuth;
    @BindView(R.id.layout_ocr)
    LinearLayout layoutOcr;
    @BindView(R.id.srl_up)
    SmartRefreshLayout srlUp;
    private BasePopupView popupView;
    private String[] levelArray = {"国家Ⅰ级重点保护", "国家Ⅱ级重点保护", "省重点保护", "其他"};
    private int[] positionArray = {-1};
    private String specId;
    private String describe;
    private String authResult;
    private boolean isValid = true;
    private String levelStr = "";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_infrared_record_pic_details;
    }

    @Override
    protected void initView() {
        super.initView();
        setModuleTitle("物种详情");
    }

    @Override
    protected void initData() {
        initPullRefresh();

    }

    @Override
    protected void getData() {
        List<String> picList = new ArrayList<>();

        List<InfraredRecordImgBean.DataBean.ListBean> list = (List<InfraredRecordImgBean.DataBean.ListBean>) getIntent().getSerializableExtra("object");
        InfraredRecordImgBean.DataBean.ListBean detailsBean = list.get(0); //这里数据是从前面传过来的，所以用get(0)获取
        String createTime = detailsBean.getCreateTime(); //识别日期
        String autoSimilar = detailsBean.getAutoSimilar(); //自动识别结果  {"麂子": 1}
        String cameraName = detailsBean.getCameraName();

        String url = detailsBean.getUrl();
        String autoUrl = detailsBean.getAutoUrl();
        specId = detailsBean.getId();

        //鉴定信息
        String auditTime = detailsBean.getAuditTime(); //鉴定日期
        String similar = detailsBean.getSimilar(); //鉴定结果
        String level = detailsBean.getLevel(); //保护级别
        String memo = detailsBean.getMemo(); //备注

        if (!StringUtils.isEmpty(autoSimilar)) {
            if (autoSimilar.indexOf(",") != -1) {
                int myNum = 0;
                String[] specArray = autoSimilar.split(","); //识别结果可能是多个，取第一个结果
                if (specArray.length > 0) {
                    String[] array = specArray[0].split(":");
                    String name = array[0].substring(2, array[0].length() - 1);
                    String num = array[1];
                    tvSpecNameAi.setText("物种名称：" + name);
                    if (!StringUtils.isEmpty(num)) {
                        myNum += Integer.parseInt(num.trim());
                    }

//                else {
//                    String[] array = specArray[i].split(":");
//                    String num = array[1].substring(0, array[1].length() - 1);
//                    if (!StringUtils.isEmpty(num)) {
//                        myNum += Integer.parseInt(num.trim());
//                    }
//                }
                    tvNum.setText("物种数量：" + myNum);
                }
            } else {
                //识别的相关信息
                String[] array = autoSimilar.split(":");
                if (array.length > 0) {
                    try {
                        String name = array[0].substring(2, array[0].length() - 1);
                        String num = array[1].substring(0, array[1].length() - 1);
                        tvSpecNameAi.setText("物种名称：" + name);
                        tvNum.setText("物种数量：" + num);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        tvTime.setText("日期：" + createTime);

        if (StringUtils.isEmpty(auditTime)) {
            layoutAuth.setVisibility(View.GONE);
        } else {
            layoutAuth.setVisibility(View.VISIBLE);
        }

        //鉴定的相关信息

        if (!StringUtils.isEmpty(similar)) {
            tvSpeName.setText("物种名称：" + similar);
        }
        if (!StringUtils.isEmpty(level)) {
            tvAuthLevel.setVisibility(View.VISIBLE);
            tvAuthLevel.setText("保护级别：" + level);
        } else {
            tvAuthLevel.setVisibility(View.GONE);
        }
        if (!StringUtils.isEmpty(auditTime)) {
            tvAuthTime.setText("日期：" + auditTime);
        }
        if (!StringUtils.isEmpty(memo)) {
            tvRemark.setVisibility(View.VISIBLE);
            tvRemark.setText("备注：" + memo);
        } else {
            tvRemark.setVisibility(View.GONE);
        }


        if (!StringUtils.isEmpty(url)) {
            picList.add(url);
        }
        if (!StringUtils.isEmpty(autoUrl)) {
            picList.add(autoUrl);
            rbBut2.setVisibility(View.VISIBLE);
            layoutOcr.setVisibility(View.VISIBLE);
        } else {
            rbBut2.setVisibility(View.GONE);
            layoutOcr.setVisibility(View.GONE);
        }

        if (picList.size() > 0) {
            InfraredRecAdapter animalBannerAdapter = new InfraredRecAdapter(context.getApplicationContext(), picList);
            banner.setAdapter(animalBannerAdapter)
                    .setIndicator(new CircleIndicator(context.getApplicationContext()), false)//设置指示器
                    .setStartPosition(0)
                    .addBannerLifecycleObserver(InfraredRecordPicDetailsActivity.this)//添加生命周期观察者
                    .addOnPageChangeListener(new OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            if (position == 0) {
                                radioGroup.check(R.id.rb_but1);
                            } else if (position == 1) {
                                radioGroup.check(R.id.rb_but2);
                            }
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    })
                    .setOnBannerListener(new OnBannerListener() {
                        @Override
                        public void OnBannerClick(Object data, int position) {
                            String url = picList.get(position);
                            boolean isHasVideo = PictureMimeType.isUrlHasVideo(url);


                            if (isHasVideo) {
                                Bundle bundle = new Bundle();
                                bundle.putString("vodeoUrl", url);
                                bundle.putString("title", createTime);
                                bundle.putBoolean("shareFlag", true);
                                IntentUtils.getInstance().readyGo(InfraredRecordPicDetailsActivity.this, VideoPlayActivity.class, bundle);
                            } else {
                                ArrayList<LocalMedia> pictureMediaList = new ArrayList<>();
                                LocalMedia localMedia = LocalMedia.generateHttpAsLocalMedia(url);
                                localMedia.setRealPath(url);
                                localMedia.setFileName(cameraName + "号红外相机" + createTime + "拍摄");
                                pictureMediaList.add(localMedia);


                                PictureSelectorStyle selectorStyle = BaseApplication.getSelectorStyle();
                                TitleBarStyle titleBarStyle = selectorStyle.getTitleBarStyle();
                                titleBarStyle.setPreviewDeleteBackgroundResource(R.mipmap.icon_three_circle);
                                selectorStyle.setTitleBarStyle(titleBarStyle);

                                PictureSelectionPreviewModel previewModel = BaseApplication.initPreviewModel();
                                previewModel.setSelectorUIStyle(selectorStyle);
                                previewModel.startActivityPreview(0, true, pictureMediaList);
                                previewModel.setExternalPreviewEventListener(new MyOnExternalPreviewEventListener(pictureMediaList));

                            }
                        }
                    });

        }

    }

    @OnClick({R.id.but, R.id.rb_but1, R.id.rb_but2})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.but:
                popupView = new XPopup.Builder(ActivityUtil.getTopActivity())
                        .moveUpToKeyboard(false) //如果不加这个，评论弹窗会移动到软键盘上面
                        .isViewMode(true)
                        .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                        .asCustom(new CenterPopup(ActivityUtil.getTopActivity()))
                        .show();
                break;
            case R.id.rb_but1:
                banner.setCurrentItem(1, true); //这块的逻辑待确定
                break;
            case R.id.rb_but2:
                banner.setCurrentItem(0, true);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁
        if (banner != null) {
            banner.destroy();
        }

        if (popupView != null) {
            popupView.destroy();
        }
    }

    private void initPullRefresh() {
        srlUp.setEnableLoadMore(false);
        srlUp.setEnableOverScrollDrag(true);
        srlUp.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                srlUp.finishRefresh(Constant.REFRESH_TIME);
                srlUp.setNoMoreData(false);
            }
        });
    }


    /**
     * 中间弹出的pop
     */
    public class CenterPopup extends CenterPopupView {

        @BindView(R.id.iv_auth)
        CheckBox ivAuth;
        @BindView(R.id.edit_auth_result)
        ContainsEmojiEditText editAuthResult;
        @BindView(R.id.layout_level)
        RelativeLayout layoutLevel;
        @BindView(R.id.edit_describe)
        ContainsEmojiEditText editDescribe;
        @BindView(R.id.tv_result)
        TextView tvResult;
        @BindView(R.id.layout_auth_content)
        LinearLayout layoutAuthContent;
        @BindView(R.id.but_commit)
        Button butCommit;

        public CenterPopup(@NonNull Context context) {
            super(context);

        }

        @Override
        protected int getImplLayoutId() {
            return R.layout.infrared_auth_popup;
        }

        @Override
        protected void onCreate() {
            super.onCreate();
            ButterKnife.bind(this);
            editDescribe.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                    describe = MyUtills.getEditText(editDescribe);
                    editDescribe.setSelection(describe.length());
                }
            });

            editAuthResult.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }

                @Override
                public void afterTextChanged(Editable s) {
                    MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                    authResult = MyUtills.getEditText(editAuthResult);
                    editAuthResult.setSelection(authResult.length());
                }
            });

            ivAuth.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    isValid = isChecked;
                    if (isValid) {
                        layoutAuthContent.setVisibility(VISIBLE);
                    } else {
                        layoutAuthContent.setVisibility(GONE);
                    }
                    MyLogUtil.e("testtest", "isChecked==" + isChecked);
                }
            });

        }

        @Override
        protected void onShow() {
            super.onShow();
        }

        @Override
        protected void onDismiss() {
            KeyboardUtils.hideSoftInput(ActivityUtil.getTopActivity());
        }

        @Override
        protected int getMaxHeight() {
            return (int) (XPopupUtils.getScreenHeight(getContext()) * .7f);
        }


        @OnClick({R.id.layout_level, R.id.but_commit})
        public void onViewClicked(View view) {
            switch (view.getId()) {
                case R.id.layout_level:
                    KeyboardUtils.hideSoftInput(this);
                    showListPop(tvResult);
                    break;
                case R.id.but_commit:
                    String str = "";
                    if (isValid) {
                        str = "确定为有效图片吗？";
                    } else {
                        str = "确定为无效图片吗？";
                    }

                    BasePopupView tipView = new XPopup.Builder(InfraredRecordPicDetailsActivity.this)
                            .isDestroyOnDismiss(true)
                            .dismissOnTouchOutside(true)
                            .hasShadowBg(true)
                            .asConfirm(context.getResources().getString(R.string.text_tip), str,
                                    context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                                    new OnConfirmListener() {
                                        @Override
                                        public void onConfirm() {
                                            identify();
                                            popupView.dismiss();
                                        }
                                    }, null, false);
                    tipView.show();


                    break;
                case R.id.rb_but1:
                    banner.setCurrentItem(0);
                    break;
                case R.id.rb_but2:
                    banner.setCurrentItem(1);
                    break;
            }
        }
    }

    /**
     * 显示列表
     */
    public void showListPop(TextView textView) {
        new XPopup.Builder(this)
                .hasShadowBg(true)
                .maxHeight(ScreenUtils.getScreenHeight() / 2)
                .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                .asCenterList("保护级别", levelArray, null, positionArray[0],
                        new OnSelectListener() {
                            @Override
                            public void onSelect(int position, String text) {
                                positionArray[0] = position;
                                levelStr = text;
                                textView.setText(text);
                            }
                        }).show();


    }

    /**
     * 专家鉴定
     */
    private void identify() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("id", specId);
        if (isValid) {
            hashMap.put("level", levelStr);
            hashMap.put("memo", describe);
            hashMap.put("similar", authResult);
        }
        hashMap.put("status", isValid ? 1 : 2);    //处理1：有效图片2：无效图片
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_INF_AUTH)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String msg = jsonObject.getString("msg");
                            if (msg.equals(Constant.RESULT_SUCCESS)) {
                                ToastUtils.showLong("鉴定完成！");
                                //这里不用做刷新操作
                                EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_INFRARED_DATA));
                                ActivityUtil.removeActivity(ActivityUtil.getTopActivity());
                            }
                        }
                    }
                });
    }

    private class MyOnExternalPreviewEventListener implements OnExternalPreviewEventListener {
        private ArrayList<LocalMedia> localMedia;
        private BasePopupView popupView;

        public MyOnExternalPreviewEventListener(ArrayList<LocalMedia> pictureMediaList) {
            this.localMedia = pictureMediaList;
        }

        @Override
        public void onPreviewDelete(int position) {
            LocalMedia media = localMedia.get(position);
            String imgUrl = media.getRealPath();
            String fileName = media.getFileName();
            String content = "绿水青山就是金山银山";
            Bitmap imageData = MyUtills.drawable2Bitmap(context.getResources().getDrawable(R.drawable.bg_shared_img));
            final OnekeyShare oks = new OnekeyShare();
            oks.setText(fileName);
            // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
            oks.setTitle(content);
            oks.setTitleUrl("https://www.mingtukeji.com");
            // text是分享文本，所有平台都需要这个字段
            //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
//                        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
            // url仅在微信（包括好友和朋友圈）中使用
            oks.setImageData(imageData);
            oks.setImageUrl(imgUrl);
            oks.setUrl(imgUrl);

            BottomPopupShare2 bottomPopup = new BottomPopupShare2(ActivityUtils.getTopActivity());
            bottomPopup.setOnItemClickListener(new BottomPopupShare2.OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    popupView.dismiss();
                    switch (position) {
                        case 0:
                            oks.setPlatform(Wechat.NAME);
                            oks.show(MobSDK.getContext());
                            break;
                        case 1:
                            oks.setPlatform(WechatMoments.NAME);
                            oks.show(MobSDK.getContext());
                            break;
                        case 2:
                            oks.setPlatform(WechatFavorite.NAME);
                            oks.show(MobSDK.getContext());
                            break;
                        case 3:
                            String path = media.getAvailablePath();
                            if (PictureMimeType.isHasHttp(path)) {
                                showMyDownLoadDialog();
                            }
                            DownloadFileUtils.saveLocalFile(context, path, media.getMimeType(), new OnCallbackListener<String>() {
                                @Override
                                public void onCall(String realPath) {
                                    hideMyDownLoadDialog();
                                    if (TextUtils.isEmpty(realPath)) {
                                        String errorMsg;
                                        if (PictureMimeType.isHasAudio(media.getMimeType())) {
                                            errorMsg = context.getString(com.luck.picture.lib.R.string.ps_save_audio_error);
                                        } else if (PictureMimeType.isHasVideo(media.getMimeType())) {
                                            errorMsg = context.getString(com.luck.picture.lib.R.string.ps_save_video_error);
                                        } else {
                                            errorMsg = context.getString(com.luck.picture.lib.R.string.ps_save_image_error);
                                        }
                                        com.luck.picture.lib.utils.ToastUtils.showToast(context, errorMsg);
                                    } else {
                                        new PictureMediaScannerConnection(ActivityUtils.getTopActivity(), realPath);
                                        com.luck.picture.lib.utils.ToastUtils.showToast(context, context.getString(com.luck.picture.lib.R.string.ps_save_success) + "\n" + realPath);
                                    }
                                }
                            });
                            break;
                    }
                }
            });
            popupView = new XPopup.Builder(ActivityUtils.getTopActivity())
                    .navigationBarColor(context.getResources().getColor(R.color.white))
                    .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
                    .asCustom(bottomPopup)
                    .show();
        }

        @Override
        public boolean onLongPressDownload(Context context, LocalMedia media) {

            return false;
        }
    }

}